package job

import (
	"fmt"
	"net/http"
	"strings"

	log "github.com/omidnikta/logrus"
)

const (
	HTTP_CONTENT_TYPE_JSON = "application/json"
)

/*
TODO:
现在只支持POST方法.
Action对象应该都是自己写的服务，和Scheduler放在同一个内网来保证api的安全性．
以后有可能需要更新本服务来支持对第三方有验证要求的API调用
*/
type Action struct {
	Addr string
	Path string
	Body string
}

func (a *Action) url() string {
	return a.Addr + a.Path
}

func (a *Action) Do() error {
	url := a.url()
	resp, err := http.Post(url, HTTP_CONTENT_TYPE_JSON, strings.NewReader(a.Body))
	if nil != err {
		log.Errorln(err)
		return err
	}
	defer resp.Body.Close()

	if http.StatusOK != resp.StatusCode {
		return fmt.Errorf("url:%s,expected statusCode %d,but got %d", url, http.StatusOK, resp.StatusCode)
	}

	return nil
}
